package com.kfh.ybracelet.chat;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.MessageBean;
import com.kfh.ybracelet.db.DatabaseManager;
import com.kfh.ybracelet.mqtt.MqttManager;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.sort.SortModel;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;

import de.greenrobot.event.EventBus;

/**
 * 联系人详情页面
 * Created by Aaron on 16/1/19.
 */
public class ContractDetailActivity extends BaseActivity {

    private ImageView ivpic;
    private TextView tvnickname;
    private TextView tvtel;
    private Button btnsend;
    private SortModel contact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_contract_detail);

        contact = getIntent().getParcelableExtra("contact");

        initWidget();

        fillData();
    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        this.btnsend = (Button) findViewById(R.id.btn_send);
        this.tvtel = (TextView) findViewById(R.id.tv_tel);
        this.tvnickname = (TextView) findViewById(R.id.tv_nickname);
        this.ivpic = (ImageView) findViewById(R.id.iv_pic);

        Button btn_delete = (Button) findViewById(R.id.btn_delete);

        iv_left.setOnClickListener(this);
        btnsend.setOnClickListener(this);
        btn_delete.setOnClickListener(this);
    }

    private void fillData() {

        if (contact == null)
            return;

        tvtel.setText(contact.phone);
        tvnickname.setText(contact.name);

        Glide.with(this)
                .load(contact.url)
                .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                .placeholder(R.mipmap.temp_pic).into(ivpic);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.btn_send:

                if (contact == null)
                    return;

                MessageBean cb = new MessageBean();
                cb.channelId = contact.topic;
                cb.receiveId = contact.phone;
                cb.receiveName = contact.name;
                cb.receivePic = contact.url;
//                cb.chatType = Constant.CHAT_SINGLE; //私聊

                //进入私聊
                Intent mIntent = new Intent(this, ChatActivity.class);
                mIntent.putExtra("contact", cb);
                startActivity(mIntent);

                break;
            case R.id.iv_left:
                finish();
                break;

            case R.id.btn_delete: //删除好友

                new AlertDialog.Builder(this).setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();

                        deleteContract();
                    }
                }).setNegativeButton("取消", null).setTitle("提醒").setMessage("删除" + contact.name).show();

                break;

        }

    }

    /**
     * 删除好友
     */
    private void deleteContract() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("phoneNum", contact.phone);

        HttpUtil.setPostRequest("正在删除中...", this, Constant.WEB_ROOT_TALK + Constant.DELFRIEND,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {
                            org.json.JSONObject result = new org.json.JSONObject(str);

//                            if (Constant.STATUS_SUCCESS == result.getInt("code")) {

                                //删除与该好友的聊天记录
                                new DeleteContractTask().execute();

//                            } else {
//                                showToast(Constant.showErrorMsg(result.getInt("code"), ContractDetailActivity.this));
//                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }


    private class DeleteContractTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {

            //通知 messageFragment 页面发生改变

            MessageBean mb = new MessageBean();
            mb.operationStyle = Constant.OFF_GROUP;
            mb.channelId = contact.topic;
            EventBus.getDefault().post(mb);

//            //取消订阅该主题
            LogUtil.e("tag", "取消订阅的主题" + contact.topic);
            MqttManager.getInstance().unSubTopic(contact.topic);

            //删除聊天记录
            DatabaseManager.getInstance().deleteHistory(ContractDetailActivity.this, contact.topic, sp.getString(Constant.USERID, ""));
            //删除topic表中的数据
            DatabaseManager.getInstance().deleteTopic(ContractDetailActivity.this, contact.topic, sp.getString(Constant.USERID, ""));

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            showToast("删除成功");
            finish();

        }
    }


}
